package com.jsonal.service.impl.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsonal.common.CommonUtil;
import com.jsonal.common.JsonUtils;
import com.jsonal.common.Md5Util;
import com.jsonal.common.ValidCode;
import com.jsonal.entity.api.User;
import com.jsonal.entity.api.UserBean;
import com.jsonal.mapper.api.UserMapper;
import com.jsonal.service.api.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsonal.util.RedisUtil;
import com.jsonal.util.SmsUtil;
import com.jsonal.util.TokenUtils;
import com.jsonal.vo.Result;
import java.util.Date;
import java.util.Random;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author auto
 * @since 2020-04-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 用户注册
     *
     * @param userBean model
     * @return res
     */
    @Override
    public Result register(UserBean userBean) {
        Result result = new Result();
        Object code = redisUtil.get(userBean.getTelephone());
        if (!userBean.getCode().equals(code)) {
            return new Result(false, "验证码错误");
        }
        User user = new User();
        BeanUtils.copyProperties(userBean, user);
        user.setCreateTime(new Date());
        user.setDelFlag(false);
        user.setPassword(Md5Util.passwordMd5(user.getPassword()));
        userMapper.insert(user);
        result.setSuccess(true);
        result.setMsg("注册成功");
        redisUtil.set(user.getUsername(), JSON.toJSON(user));
        return result;
    }

    /**
     * 根据手机号获取验证码
     *
     * @param telephone 手机号
     * @return res
     */
    @Override
    public Result getValidCode(String telephone) {
        Result result = new Result();
        String code = ValidCode.getCode();
        try {
            String json = "{\"code\" : " + code + "} ";
            SendSmsResponse sendSmsResponse = SmsUtil.sendSms(telephone, json);
            String message = sendSmsResponse.getMessage();
            redisUtil.set(telephone, code, 5 * 60);
            result.setSuccess(true);
            result.setMsg(message);
            return result;
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 登录
     *
     * @param userBean model
     * @return res
     */
    @Override
    public Result login(UserBean userBean) {
        Result result = new Result();
        try {
            Object obj = redisUtil.get(userBean.getUsername());
            if (obj == null) {
                // redis 中不存在用户，此时应该去数据库查询
                User user = userMapper
                    .selectOne(new QueryWrapper<User>().eq("username", userBean.getUsername()));
                if (user == null) {
                    return new Result(false, "用户不存在");
                }
                String token = user.getUsername() + "_" + user.getPassword() + new Random().nextInt(1000);
                UserBean bean = new UserBean();
                BeanUtils.copyProperties(user, bean);
                redisUtil.set(token, String.valueOf(System.currentTimeMillis()), 60 * 30);
                redisUtil.set(user.getUsername(), JSON.toJSON(user));
                bean.setToken(token);
                result.setSuccess(true);
                result.setMsg("登录成功");
                result.setObj(bean);
                return result;
            } else {
                if (!userBean.getCode().equalsIgnoreCase((String) redisUtil.get("_code"))) {
                    return new Result(false, "验证码错误");
                }
                User user = JsonUtils.jsonToPojo(obj.toString(), User.class);
                if (!Md5Util.passwordMd5(userBean.getPassword())
                    .equals(user.getPassword())) {
                    return new Result(false, "用户名密码错误");
                } else {
                    UserBean bean = new UserBean();
                    BeanUtils.copyProperties(user, bean);
                    String token = user.getUsername() + "_" + user.getPassword() + new Random().nextInt(1000);
                    redisUtil.set(token, String.valueOf(System.currentTimeMillis()), 60 * 30);
                    bean.setToken(token);
                    result.setSuccess(true);
                    result.setMsg("登录成功");
                    result.setObj(bean);
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 分页获取用户列表
     *
     * @param userBean model
     * @return res
     */
    @Override
    public Result getUserList(UserBean userBean) {
        Result result = new Result();
        IPage<User> page = new Page<>(userBean.getPage(), userBean.getPageSize());
        IPage<User> users = null;
        if (userBean.getQuery() != null && !"".equals(userBean.getQuery())) {
            users = userMapper.selectPage(page,
                new QueryWrapper<User>().
                    eq("del_flag", false)
                    .and(i -> i.like("username", userBean.getQuery()))
                    .or(i -> i.like("telephone", userBean.getQuery()))
                    .orderByDesc("create_time")
            );
        } else {
            users = userMapper.selectPage(page,
                new QueryWrapper<User>().
                    eq("del_flag", false).
                    orderByDesc("create_time"));
        }
        if (users.getSize() > 0) {
            result.setSuccess(true);
            result.setResults(users.getRecords());
            result.setObj(users);
            return result;
        }
        result.setSuccess(false);
        return result;
    }

    /**
     * 根据用户 id 修改状态
     *
     * @param id 用户 id
     * @param state 修改后的状态
     * @return res
     */
    @Override
    public Result changeState(String id, Boolean state) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("id", id));
        if (user == null) {
            return new Result(false, "用户不存在");
        }
        user.setState(state);
        int i = userMapper.updateById(user);
        if (i > 0) {
            return new Result(true, "更新成功");
        }
        return new Result(false, "未知错误");
    }

    /**
     * 添加或修改用户
     *
     * @param userBean 用户实体
     * @return res
     */
    @Override
    public Result addOrUpdate(UserBean userBean) {
        Result result = new Result();
        User user = new User();
        BeanUtils.copyProperties(userBean, user);
        // 判断 id 是否有值，有值即是编辑修改 无值就是新增
        if (userBean.getId() != null) {
            user.setUpdateTime(new Date());
            int update = userMapper.updateById(user);
            if (update > 0) {
                result.setSuccess(true);
                return result;
            }
            result.setSuccess(false);
            return result;
        } else {
            user.setCreateTime(new Date());
            user.setDelFlag(false);
            int insert = userMapper.insert(user);
            if (insert > 0) {
                result.setSuccess(true);
                return result;
            }
            result.setSuccess(false);
            return result;
        }
    }

    /**
     * 根据用户 id 获取信息
     *
     * @param id 用户 id
     * @return res
     */
    @Override
    public Result getUserById(String id) {
        Result result = new Result();
        User user = userMapper
            .selectOne(new QueryWrapper<User>().eq("id", id).eq("del_flag", false));
        if (user != null) {
            result.setSuccess(true);
            result.setObj(user);
            return result;
        }
        result.setSuccess(false);
        result.setMsg("用户不存在");
        return result;
    }

    /**
     * 根据用户 id 删除用户 逻辑删除
     *
     * @param id 用户 id
     * @return res
     */
    @Override
    public Result removeUser(String id) {
        Result result = new Result();
        // 先从数据库查询是否存在该用户 不存在则返回 存在则修改
        User user = userMapper
            .selectOne(new QueryWrapper<User>().eq("id", id).eq("del_flag", false));
        if (user == null) {
            return new Result(false, "用户不存在");
        }
        user.setDelFlag(true);
        int update = userMapper.updateById(user);
        if (update > 0) {
            result.setSuccess(true);
            result.setMsg("删除成功");
            return result;
        }
        result.setSuccess(false);
        result.setMsg("删除失败");
        return result;
    }

    /**
     * 根据用户 token 获取用户信息
     *
     * @param userBean bean
     * @return res
     */
    @Override
    public Result getUserInfo(UserBean userBean) {
        Result result = new Result();
        if (userBean.getUsername() == null) {
            return new Result(false, "token不存在");
        }
        User user = userMapper
            .selectOne(new QueryWrapper<User>()
                .eq("username", userBean.getUsername())
                .eq("del_flag", false)
            );
        if (user == null) {
            return new Result(false, "用户不存在");
        }
        result.setObj(user);
        result.setSuccess(true);
        return result;
    }
}
